/*
 * replaceContentDesField() 替换内容说明字段值
 * options - 下拉选择的业务类型数组
 * */
export function replaceContentDesField(options) {
    let reg = /{(.+?)}/gi;
    options.forEach(opOne => {
        opOne.afterReplaceContentCopy = JSON.parse(JSON.stringify(opOne.typeContent));
        let value = opOne.typeContent ? opOne.typeContent.match(reg) : ""; //处理内容说明里面的变量
        opOne.afterReplaceContentField = [];
        if (value) {
            for (var i = 0; i < value.length; i++) {
                const cnPram = value[i];
                const cnName = cnPram.replace(reg, "$1");
                opOne.afterReplaceContentField.push(cnName);
            }
        }
    });
}

export function getBusinessData(
    store,
    location,
    type,
    typeId = null,
    formData = null,
    isFillsign = false,
) {
    /*
     * type  获取类型值
     * typeId 当类型是workflowModule时配置的值
     * formData 外传入的对象值
     * isFillsign 是否是补签页面，有选择框true
     * */
    /** 从后台获取业务类型，清单业务类型，过滤条件业务类型*/
    let reData = null;
    const user = store.user;
    if (user.basicBusinessDataList && user.basicBusinessDataList.length === 0) {
        store.getBaseBusinessData().then(data => {
            if (user.activeTabsMenu.length) {
                reData = processDataFunction(store, location, type, typeId, formData, isFillsign);
            }
        });
    } else {
        if (user.activeTabsMenu.length) {
            reData = processDataFunction(store, location, type, typeId, formData, isFillsign);
        }
    }

    return reData;
}

function processDataFunction(store, location, type, typeId, formData, isFillsign) {
    const basicBusinessDataList = store.user.basicBusinessDataList;
    // 获取激活菜单
    const currentPath = location.pathname.replace(/\/detail/, "");
    const singleDataItem = basicBusinessDataList.find(opItem => {
        if (currentPath === opItem.modelPath) {
            // 过滤不启用的项
            opItem.options = opItem.options.filter(xOne => xOne.isUse === 1) || opItem.options;
            return opItem;
        }
    });

    // 处理内容说明字段
    if (singleDataItem) {
        if (singleDataItem.options) {
            replaceContentDesField(singleDataItem.options);
        }

        if (type === "options") {
            // 业务类型
            return singleDataItem.options || [];
        } else if (type === "path") {
            return singleDataItem.modelPath;
        } else if (type === "columns") {
            if (checkIsJSON(singleDataItem.columns)) {
                // let cols = JSON.parse(singleDataItem.columns);
                // if (isFillsign) {
                //     // 补签
                //     cols.unshift({
                //         type: "selection",
                //         width: 60,
                //         align: "center",
                //     });
                // }
                // cols = cols.map((itemsCol, i) => {
                //     if (itemsCol && itemsCol.click) {
                //         itemsCol.click = that[itemsCol.click] || null; // || that.$message({type:'info',message:'表格点击无效，请稍后重试！'})
                //     }
                //     if (itemsCol && itemsCol.btns && itemsCol.btns.length) {
                //         itemsCol.btns.forEach((itemsColForBtns, j) => {
                //             if (itemsColForBtns && itemsColForBtns.click) {
                //                 itemsColForBtns.click = that[itemsColForBtns.click] || null; //  || that.$message({type:'info',message:'表格按钮点击无效，请稍后重试！'})
                //             }
                //         });
                //         if (isFillsign) {
                //             // 补签，操作只留预览
                //             itemsCol.btns = itemsCol.btns.filter(isBtns => {
                //                 return isBtns.prop === "viewPdf";
                //             });
                //         }
                //     }
                //     return itemsCol;
                // });
                // return cols;
            } else {
                console.error("columns不是json格式数据");
                return null;
            }
        } else if (type === "buttons") {
            //表单字段
            if (checkIsJSON(singleDataItem.buttons)) {
                // let cols = JSON.parse(singleDataItem.buttons);
                // cols = cols.map((itemsCol, i) => {
                //     if (itemsCol && itemsCol.props && itemsCol.props.click) {
                //         itemsCol.props.click = that[itemsCol.props.click];
                //     }
                //     return itemsCol;
                // });
                // return cols;
            } else {
                console.error("buttons不是json格式数据");
                return null;
            }
        } else if (type === "tableId") {
            return singleDataItem.tableId;
        } else if (type === "listTableId") {
            return singleDataItem.listTableId;
        } else if (type === "dbName") {
            return singleDataItem.dbName;
        } else if (type === "baseUrl") {
            return singleDataItem.baseUrl;
        } else if (type === "workflowModule") {
            let wflowModuleValue = null;
            if (singleDataItem.workflowModule) {
                wflowModuleValue = singleDataItem.workflowModule;
            } else {
                if (typeId) {
                    // 获取业务类型数据里面的工作流配置
                    const resOpt = singleDataItem.options.find(item => {
                        return item.value == typeId;
                    });
                    if (resOpt) {
                        wflowModuleValue = resOpt.workflowModule;
                    } else {
                        wflowModuleValue = null;
                    }
                } else {
                    // 默认第一项
                    wflowModuleValue =
                        (singleDataItem.options &&
                            singleDataItem.options.length &&
                            singleDataItem.options[0].workflowModule) ||
                        null;
                }
            }
            return wflowModuleValue;
        } else if (type === "useWorkflow") {
            //配置了，工作流拼接业务的字段
            let useWorkflowVal = null;
            if (singleDataItem.useWorkflow) {
                useWorkflowVal = singleDataItem.useWorkflow;
            } else {
                if (typeId) {
                    // 获取业务类型数据里面的工作流配置
                    const resOpt = singleDataItem.options.find(item => {
                        return item.value == typeId;
                    });
                    if (resOpt) {
                        useWorkflowVal = resOpt.useWorkflow;
                    } else {
                        useWorkflowVal = null;
                    }
                } else {
                    // 默认第一项
                    useWorkflowVal =
                        (singleDataItem.options &&
                            singleDataItem.options.length &&
                            singleDataItem.options[0].useWorkflow) ||
                        null;
                }
            }
            return useWorkflowVal;
        } else if (type === "modelName") {
            return singleDataItem.modelName;
        } else if (type === "projId") {
            return singleDataItem.projId;
        } else if (type === "optionOne") {
            const optionOne = singleDataItem.options.find(item => {
                return item.value == typeId || item.tableId == typeId;
            });
            return optionOne;
        } else if (type === "mainWork") {
            let typeContent = null;
            if (typeId) {
                // 获取业务类型数据里面的工作流配置
                typeContent =
                    singleDataItem.options.find(item => {
                        return item.value == typeId;
                    }).typeContent || null;
            } else {
                // 默认第一项
                typeContent =
                    (singleDataItem.options &&
                        singleDataItem.options.length &&
                        singleDataItem.options[0].typeContent) ||
                    null;
            }
            return typeContent;
        } else if (type === "singleItem") {
            return singleDataItem;
        } else {
            return "传参";
        }
    } else {
        if (type === "listOptions") {
            // 清单类型
            let listOptions = basicBusinessDataList.filter(opItemOne => {
                return opItemOne.isHaveType === 1;
            });
            return listOptions;
        }
    }
}

/*
 * changeContentField() 替换内容说明字段值
 * optionsOne - 下拉选择的业务类型对象
 * formData - 业务数据对象
 * */
export function changeContentField(optionsOne, formData, typeId, page, projTypeId) {
    let changeCopyFieldValue = null;
    if (projTypeId) {
        // 切换业务类型
        changeCopyFieldValue = optionsOne.afterReplaceContentCopy;
    } else {
        if ((page === "edit" || page === "view" || page === "sign") && formData.mainWorkPdf) {
            changeCopyFieldValue = formData.mainWorkPdf;
            changeCopyFieldValue = matchConFiled(formData.mainWorkPdf);
        }
    }
    const optionsField = optionsOne && optionsOne.afterReplaceContentField;
    if (optionsField && optionsField.length > 0) {
        optionsField.forEach(item => {
            changeCopyFieldValue = changeFormData(
                changeCopyFieldValue,
                optionsOne,
                item,
                formData,
                typeId,
            );
        });
        return changeCopyFieldValue;
    } else {
        return optionsOne && optionsOne.typeContent;
    }
}

function changeFormData(changeCopyFieldValue, optionsOne, item, formData, typeId) {
    let reg = item.trim();
    let regSplit = reg.split("-");
    let reg1 = regSplit[0]; // 值
    let reg2 = "date"; //格式 'date','dateTime','dateRange' 格式例如：'2024年02年02日' , '2024年02年02日 02时02分02秒','2024年02月02日-2024年02月03日'
    let isUseFormat = null; // 配置是否单独设置格式
    let isDate = null; //是否时间格式
    const isDateObj = Object.prototype.toString.call(formData[reg1]) === "[object Date]";
    if (regSplit && regSplit.length > 1) {
        // debugger;
        // 时间会存格式
        isDate = true;
        reg2 = regSplit[1];
        isUseFormat = "-" + reg2;
        if (reg2 === "dateRange") {
            // 时间范围（至）
            if (formData[reg1]) {
                const d1 = formData[reg1].split("至")[0],
                d2 = formData[reg1].split("至")[1];
                const date1 = d1 && new Date(d1);
                const date2 = d2 && new Date(d2);
                const isDateObj1 = Object.prototype.toString.call(date1) === "[object Date]";
                const isDateObj2 = Object.prototype.toString.call(date2) === "[object Date]";
                if (isDateObj1 && isDateObj2) {
                    // 日期范围选择器
                    formData["contractNo"] =
                    formatDateTime(date1, "date") + "至" + formatDateTime(date2, "date"); // 存时间的中文格式
                }
            }
        } else if (reg2 === "dateTime") {
            if (isDateObj) {
                // 日期时间选择器
                formData["contractNo"] = formatDateTime(formData[reg1], "datetime"); // 存时间的中文格式
            }
        }
    } else {
        if (isDateObj) {
            // 日期时间选择器
            formData["contractNo"] = formatDateTime(formData[item], reg2); // 存时间的中文格式
            formData[reg1] = formatDateTime(formData[item]);
            isDate = true;
        }
        const isStringDateObj = checkTimeFormat(formData[reg1]); // 校验是否是时间字符串
        if (isStringDateObj) {
            const formDataDate = new Date(formData[reg1]);
            const isDateObj2 = Object.prototype.toString.call(formDataDate) === "[object Date]";
            if (isDateObj2) {
                formData["contractNo"] =
                    formData["contractNo"] || formatDateTime(formDataDate, reg2); // 存时间的中文格式
                formData[reg1] = formData[reg1].substring(0, 10);
                isDate = true;
            }
        }
    }
    const acopy = changeCopyFieldValue || optionsOne.afterReplaceContentCopy;
    const contentTxt = changeCopyField(acopy, reg1, isDate, isUseFormat, formData, typeId);
    return contentTxt;
}

function matchConFiled(str) {
    // 使用正则表达式删除所有${与|之间的内容,并且将}$删除
    str = str.replace(/\|([^}]*)\}\$/g, "}").replace(/\$\{/g, "{"); // .replaceAll('}$', '')
    return str;
}

function checkIsJSON(str) {
    if (typeof str == "string") {
        try {
            var obj = JSON.parse(str);
            if (typeof obj == "object" && obj) {
                return true;
            } else {
                return false;
            }
        } catch (e) {
            return false;
        }
    }
    return false;
}

function checkTimeFormat(timeStr) {
    var timeFormat = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/;
    return timeFormat.test(timeStr);
}

/*
 * 处理替换字段
 * */
function changeCopyField(aCopy, item, isDate, isUseFormat, formData, typeId) {
    if (`{${item}}` === `{checked}`) {
        // 选中框
        aCopy = aCopy.replace(`{${item}}`, "");
    } else if (`{${item}}` === `{${formData[typeId]}}`) {
        // 选中框
        aCopy = aCopy.replace(`{${formData[typeId]}}`, "☑ ");
    } else {
        if (Number(item) > 0) {
            //选框置空白框
            aCopy = aCopy.replace(`{${item}}`, "☐ ");
        } else {
            // 替换值
            let curItem = `{${item}}`;
            // let curFormData1 = (formData[item] || '')  // 值
            let curFormData2 = "${" + item + "|" + (formData[item] || "") + "}$"; // ${值}$
            let curFormData3 = "${" + item + "|" + (formData["contractNo"] || "") + "}$"; // ${值-时间}$
            if (isDate) {
                if (isUseFormat) {
                    curItem = `{${item}${isUseFormat}}`;
                    curFormData3 =
                        "${" + item + isUseFormat + "|" + (formData["contractNo"] || "") + "}$"; // ${值-时间}$
                }
                aCopy = aCopy.replace(curItem, curFormData3);
            } else {
                aCopy = aCopy.replace(curItem, curFormData2);
            }
        }
    }
    return aCopy;
}

function formatDateTime(date, type) {
    if (typeof date !== "string") {
        date = new Date(date);
        let year = date.getFullYear() + "";
        let month =
            date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1 + "";
        let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate() + "";
        let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours() + "";
        let minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes() + "";
        let second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds() + "";
        if (type == 1 || type == 'date' || type == "yyyy年MM月dd日") {
            return year + "年" + month + "月" + day + "日";
        } else if (type == 2 || type == "yyyy-MM-dd HH:mm:ss" || type == "yyyy-MM-dd hh:mm:ss") {
            return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
        } else if (
            type == 3 ||
            type == "yyyy年MM月dd日 HH时mm分ss秒" ||
            type == "yyyy年MM月dd日 hh时mm分ss秒"
        ) {
            return (
                year +
                "年" +
                month +
                "月" +
                day +
                "日 " +
                hour +
                "时" +
                minute +
                "分" +
                second +
                "秒"
            );
        } else {
            return year + "-" + month + "-" + day;
        }
    } else {
        return date;
    }
}
